package com.example.model;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class LocationModel extends SQLiteOpenHelper {
	private final static String DATABASE_NAME = "LOCATION.db";
	private final static int DATABASE_VERSION = 1;
	private final static String TABLE_NAME = "location_table";
	public final static String LOCATION_ID = "location_id";
	public final static String LOCATION_NAME = "location_name";
	public final static String CURRENT_LOCATION = "current_location";

	public LocationModel(Context context) {
		// TODO Auto-generated constructor stub
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	// 创建table
	@Override
	public void onCreate(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + TABLE_NAME + " (" + LOCATION_ID
				+ " INTEGER primary key autoincrement, " + LOCATION_NAME
				+ " text, " + CURRENT_LOCATION + " text);";
		db.execSQL(sql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
		db.execSQL(sql);
		onCreate(db);
	}

	public Cursor select() {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db
				.query(TABLE_NAME, null, null, null, null, null, null);
		return cursor;
	}

	// 增加操作
	public long insert(String locname, String curloc) {
		SQLiteDatabase db = this.getWritableDatabase();
		/* ContentValues */
		ContentValues cv = new ContentValues();
		cv.put(LOCATION_NAME, locname);
		cv.put(CURRENT_LOCATION, curloc);
		long row = db.insert(TABLE_NAME, null, cv);
		return row;
	}

	// 删除操作
	public void delete(int id) {
		SQLiteDatabase db = this.getWritableDatabase();
		String where = LOCATION_ID + " = ?";
		String[] whereValue = { Integer.toString(id) };
		db.delete(TABLE_NAME, where, whereValue);
	}

	// 修改操作
	public void update(int id, String locname, String curloc) {
		SQLiteDatabase db = this.getWritableDatabase();
		String where = LOCATION_ID + " = ?";
		String[] whereValue = { Integer.toString(id) };

		ContentValues cv = new ContentValues();
		cv.put(LOCATION_NAME, locname);
		cv.put(CURRENT_LOCATION, curloc);
		db.update(TABLE_NAME, cv, where, whereValue);
	}
   //查询
	public String query(String locationName) {
		SQLiteDatabase db = this.getWritableDatabase();

		Cursor result = db.query(TABLE_NAME, new String[] { LOCATION_NAME,
				CURRENT_LOCATION }, LOCATION_NAME + "='" + locationName + "'",
				null, null, null, null);
		int resultCount = result.getCount();
		if (resultCount == 0 || !result.moveToFirst()) {
			return null;
		}

		String currentLocation = result.getString(result
				.getColumnIndex(CURRENT_LOCATION));
		return currentLocation;
	}

}